﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SalaDeEnsayo.WebApplication.SecurityAttributes;
using SalaDeEnsayo.ApplicationService;
using SalaDeEnsayo.ApplicationService.Model.Entity;

namespace SalaDeEnsayo.WebApplication
{
    [RolUsuario]
    [RolAdminSistema]
    public partial class GestionHorarios : System.Web.UI.Page
    {
        private static Reserva reserva;
        private static eAccion action;

        public GestionHorarios()
        {
            //reserva = new Reserva();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDropDownList();
                BindSchedule();
                Inicializar();
            }

        }

        #region [ Metodos Privados ]

        /// Cambiar despues en la capa servicio de Salas
        /// 
        private void LoadDropDownList()
        {
            GrupoService grupoS = new GrupoService();
            EstadoService estadoS = new EstadoService();
            SalaService salaS = new SalaService();

            List<Grupo> listaGrupo = grupoS.GetAll();
            List<Estado> listaEstado = estadoS.EstadosObtener();
            List<Sala> listaSala = salaS.ObtenerSalas();

            ReservaService reservaS = new ReservaService();
            ddlSalas.Items.Clear();
            ddlSalas.Items.AddRange(listaSala.Select(s=>new ListItem(s.Nombre,s.Id_Sala.ToString())).ToArray());
            

            ddlSala.Items.Clear();
            ddlSala.Items.Add(new ListItem("--Seleccione--", "0"));
            ddlSala.Items.AddRange(listaSala.Select(s => new ListItem(s.Nombre, s.Id_Sala.ToString())).ToArray());

            ddlGrupo.Items.Clear();
            ddlGrupo.Items.Add(new ListItem("--Seleccione--","0"));
            ddlGrupo.Items.AddRange(listaGrupo.Select(g=> new ListItem(g.Nombre_grupo,g.Id.ToString())).ToArray());

            ddlEstado.Items.Clear();
            ddlEstado.Items.Add(new ListItem("--Seleccione","0"));
            ddlEstado.Items.AddRange(listaEstado.Select(e=> new ListItem(e.NombreEstado,e.Id.ToString())).ToArray());

            
        }

        private void BindSchedule()
        {
            ReservaService reservaS = new ReservaService();
            DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;
            grdSchedule.DataSource = reservaS.ObtenerPorSalaPorDia(selectedDate,int.Parse(ddlSalas.SelectedValue));
            grdSchedule.DataBind();
            this.lblFecha.Text = "Fecha seleccionada: " + selectedDate.ToString("dd/MM/yyyy");
        }

        private void cargarDdlHoraSalida() 
        {
            DateTime a = new DateTime();
            DateTime b = new DateTime();
            Int32 i=1;
            string min, hora;
            
            ddlHoraSalida.Items.Clear();

            
            a= Convert.ToDateTime("01/01/2011 "+ txtHoraEntrada.Text+":00");
            b = Convert.ToDateTime("02/01/2011 00:00:00");
            a = a.AddHours(1);

            ddlHoraSalida.Items.Add(new ListItem("--Seleccione", "0"));

            while (i<7) 
            {
                min = a.Minute.ToString();
                hora = a.Hour.ToString();

                if (a.Equals(b)) 
                {
                    break;
                }

                if (min == "0")
                {
                    min = "00";
                }

                if (hora.Length == 1)
                {
                    hora = "0" + hora;
                }

                ddlHoraSalida.Items.Add(new ListItem(hora+ ":"+min,i.ToString()));
                a = a.AddHours(1);
                i++;
            }

        
        }

        #endregion

        #region [ Eventos ]

        protected void CalendarManager_SelectionChanged(object sender, EventArgs e)
        {
            BindSchedule();
        }

        protected void ddlSalas_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindSchedule();
        }

        protected void grdSchedule_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdSchedule.PageIndex = e.NewPageIndex;
            BindSchedule();
        }

        protected void btnAgregar_OnClick(object sender, EventArgs e)
        {
            string[] var = ((ImageButton)sender).CommandArgument.Split(';');
            DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;

            LimpiarCampos();

            DateTime fecha=new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(var[0]), 0, 0);

            if (fecha >= DateTime.Now)
            {

                txtHoraEntrada.Text = var[0].Length == 1 ? "0" + var[0] + ":00" : var[0] + ":00";


                reserva = new Reserva();
                pnlReserva.GroupingText = "Agregar Reserva";
                pnlReserva.Enabled = true;
                btnGuardar.Visible = true;
                btnGuardar.Enabled = true;
                btnCancelar.Visible = true;
                btnCancelar.Enabled = true;

                ddlSala.SelectedIndex = ddlSalas.SelectedIndex + 1;
                cargarDdlHoraSalida();
                action = eAccion.Agregar;
                EstadoCampos(true);

                txtHoraEntrada.Enabled = false;
                txtSaldo.Enabled = false;
                ddlEstado.Enabled = false;
                EstadoValidator.Enabled = false;
            }
            else {
                Master.ShowMessage("No puede generar una reserva en el día seleccionado.");
            }
        }


        private void LimpiarCampos()
        {
            ddlGrupo.SelectedValue = "0";
            ddlSala.SelectedIndex = 0;
            ddlHoraSalida.SelectedIndex = -1;
            txtHoraEntrada.Text = string.Empty;
            txtSenia.Text = string.Empty;
            txtSaldo.Text = string.Empty;
            ddlEstado.SelectedValue = "0";
        }

        protected void btnModificar_OnClick(object sender, EventArgs e)
        {
            string[] var = ((ImageButton)sender).CommandArgument.Split(';');
            ReservaService reservaS = new ReservaService();
            DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;
            reserva = reservaS.ObtenerPorDiaHora(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(var[0]), 0, 0));


            DateTime fecha=new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(var[0]), 0, 0);

            if ((reserva.IdEstado == 1 && fecha <= DateTime.Now) || fecha >= DateTime.Now)
            {
                LoadForm(reserva);

                pnlReserva.GroupingText = "Editar Reserva";
                pnlReserva.Enabled = true;
                btnGuardar.Visible = true;
                btnGuardar.Enabled = true;
                btnEliminar.Visible = false;
                btnCancelar.Visible = true;
                action = eAccion.Modificar;

                //SI Solo puedo modificar el saldo y el estado.
                if (reserva.IdEstado == 1 && fecha <= DateTime.Now)
                {
                    EstadoCampos(false);
                    txtHoraEntrada.Enabled = false;
                    EstadoValidator.Enabled = true;
                    //Nuevo
                    txtSaldo.Enabled = true;
                    ddlEstado.Enabled = true;
                }
                else
                {
                    EstadoCampos(true);
                    txtHoraEntrada.Enabled = false;
                    EstadoValidator.Enabled = true;
 
                }
            }
            else
            {
                Master.ShowMessage("No puede modificar reservas que ya han sido cerradas.");
            }

        }

        

        protected void btnBorrar_OnClick(object sender, EventArgs e)
        {
            string[] var = ((ImageButton)sender).CommandArgument.Split(';');
            ReservaService reservaS = new ReservaService();
            DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;
            reserva = reservaS.ObtenerPorDiaHora(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(var[0]), 0, 0));

            
            DateTime fecha=new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(var[0]), 0, 0);

            if (fecha >= DateTime.Now)
            {

                LoadForm(reserva);

                pnlReserva.GroupingText = "Confirmar Borrado";
                pnlReserva.Enabled = true;

                EstadoCampos(false);

                btnGuardar.Visible = false;
                btnEliminar.Visible = true;
                btnEliminar.Enabled = true;
                btnCancelar.Visible = true;
                btnCancelar.Enabled = true;

                EstadoValidator.Enabled = false;
            }
            else
            {
                Master.ShowMessage("No puede anular reservas que ya han sido cerradas.");
            }

        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            Inicializar();
            LimpiarCampos();
        }

        private void LoadForm(Reserva res)
        {
            ddlGrupo.SelectedValue = res.IdGrupo.ToString();
            ddlSala.SelectedValue = res.IdSala.ToString();
            txtHoraEntrada.Text = res.HorarioEntrada.ToString("HH:mm");
            txtHoraEntrada.Enabled = false;
            cargarDdlHoraSalida();

            ddlHoraSalida.SelectedValue = ddlHoraSalida.Items.FindByText(res.HorarioSalida.ToString("HH:mm")).Value;

            txtSenia.Text = res.Senia.ToString();
            txtSaldo.Text = res.Saldo.ToString();
            ddlEstado.SelectedValue = res.IdEstado.ToString();
            ddlEstado.Enabled = true;
            
        }
        #endregion

        protected void EstadoCampos(Boolean estado) 
        {
            ddlSala.Enabled = estado;
            ddlEstado.Enabled = estado;
            ddlGrupo.Enabled = estado;
            ddlHoraSalida.Enabled = estado;
            txtHoraEntrada.Enabled = estado;
            txtSaldo.Enabled = estado;
            txtSenia.Enabled = estado;
        }

        protected void btnGuardar_Click(object sender, EventArgs e)
        {
            ReservaService reservaS = new ReservaService();
            DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;
            DateTime hSalida, hEntrada;

            string hs = ddlHoraSalida.SelectedItem.Text;

            string[] horaEntrada = txtHoraEntrada.Text.Split(':');
            string[] horaSalida = hs.Split(':');

            hEntrada= new DateTime(selectedDate.Year,selectedDate.Month,selectedDate.Day,int.Parse(horaEntrada[0].ToString()), int.Parse(horaEntrada[1].ToString()),0);
            hSalida= new DateTime(selectedDate.Year,selectedDate.Month,selectedDate.Day,int.Parse(horaSalida[0].ToString() ), int.Parse(horaSalida[1].ToString()),0);


           
                reserva.IdGrupo = long.Parse(ddlGrupo.SelectedValue.ToString());
                reserva.IdSala = int.Parse(ddlSala.SelectedValue.ToString());
                reserva.HorarioEntrada=hEntrada;
                reserva.HorarioSalida = hSalida;
                reserva.Senia = decimal.Parse(txtSenia.Text);

                if (action == eAccion.Modificar)
                {
                    reserva.IdEstado = int.Parse(ddlEstado.SelectedValue.ToString());
                    reserva.Saldo = decimal.Parse(txtSaldo.Text);
                }
                else 
                {
                    reserva.Saldo = 0;
                }


                if (reservaS.AgerarModificarReserva(reserva) != 0)
                {

                    if (action == eAccion.Agregar)
                        Master.ShowMessage("La reserva se registró correctamente");
                    else
                        Master.ShowMessage("La reserva se actualizó correctamente");
                }
                else
                {
                    Master.ShowError("Ocurrió un problema inesperado, por favor intente mas tarde");
                }

                LimpiarCampos();
                Inicializar();
                BindSchedule();
          

            
        }

        private void Inicializar()
        {
            pnlReserva.Enabled = false;
            btnGuardar.Enabled = false;
            btnEliminar.Enabled = false;
            pnlReserva.GroupingText = "Reserva";
            lblErrorHora.Visible = false;
            btnGuardar.Visible = false;
            btnEliminar.Visible = false;
            btnCancelar.Visible = false;

            DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;
            this.lblFecha.Text = "Fecha seleccionada: " + selectedDate.ToString("dd/MM/yyyy");
        }

        protected void btnEliminar_Click(object sender, EventArgs e)
        {
            ReservaService reservaS = new ReservaService();

            if (reservaS.BorrarReserva(reserva) != 0)
            {
                Master.ShowMessage("La reserva se borró correctamente");
            }
            else
            {
                Master.ShowError("Ocurrió un problema inesperado, por favor intente mas tarde");
            }
           

            LimpiarCampos();
            Inicializar();
            BindSchedule();

        }

        protected void ddlHorarioSalida_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlHoraSalida.SelectedIndex != 0)
            {

                ReservaService reservaS = new ReservaService();
                DateTime selectedDate = CalendarManager.SelectedDate == DateTime.MinValue ? CalendarManager.TodaysDate : CalendarManager.SelectedDate;
                DateTime hSalida, hEntrada;

                string hs = ddlHoraSalida.SelectedItem.Text;

                string[] horaEntrada = txtHoraEntrada.Text.Split(':');
                string[] horaSalida = hs.Split(':');

                hEntrada = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(horaEntrada[0].ToString()), int.Parse(horaEntrada[1].ToString()), 0);
                hSalida = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, int.Parse(horaSalida[0].ToString()), int.Parse(horaSalida[1].ToString()), 0);

                if (!reservaS.PuedeInsertar(hEntrada, hSalida, int.Parse(ddlSala.SelectedValue), reserva.Id))
                {
                    lblErrorHora.Visible = true;
                    btnGuardar.Enabled = false;
                }
                else
                {
                    lblErrorHora.Visible = false;
                    btnGuardar.Enabled = true;
                }
            }
            
        }
               

        private enum eAccion
        {
            Agregar = 0,
            Modificar = 1
        }



    }
}
